package com.example.securitydemos.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

/**
 * @author linjy on 2023/1/12
 * 前后端分离时处理json响应信息
 */
//@EnableWebSecurity
public class SecurityConfig_基于内存授权 extends WebSecurityConfigurerAdapter {


    /**
     *  没有登录就会进入登录页面http://localhost:8080/login
     *  角色认证不通过就会报403错误
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .hasAnyRole("USER", "ADMIN")
                .antMatchers("/visitor/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }


    /**
     * 内存中创建多个用户角色的方式1:
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser(User.withUsername("admin").password("123").roles("ADMIN", "USER").build())
                .withUser(User.withUsername("user").password("123").roles("USER").build())
                //设置密码编码器
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    /**
     * 内存中创建多个用户角色的方式2:
     * 基于内存的多用户支持.在内存中创建多个用户与角色.
     */
    /*@Bean
    public UserDetailsService createUserDetailService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();

        //在内存中创建admin与user用户
        manager.createUser(User.withUsername("admin").password("123").roles("ADMIN", "USER").build());
        manager.createUser(User.withUsername("user").password("123").roles("USER").build());
        return manager;
    }*/

    /**
     * 由于5.x版本之后默认启用了委派密码编码器,因而按照以往的方式设置内存密码将会读取异常,所在需要暂时将密码编码器设置为NoOpPasswordEncoder.
     * 后面我们可以修改成BCryptPasswordEncoder.
     * 这里必须设置一个密码编码器,否则无法通过对用户名和密码的验证.
     */
    /*@Bean
    public PasswordEncoder passwordEncoder() {
        //return new BCryptPasswordEncoder();
        return NoOpPasswordEncoder.getInstance();
    }*/


}